/**
 * jusetoken middlewares
 * code by pange
 * 2017-4-7
 * 
 */
/**
 * 权限认证设计思路
 * 
 * 1.获取token，取出tree
 * 2.获取req.originalUrl
 * 3.处理url  去掉‘／’
 * 4.判断 3是否在1中
 */
var bcrypt = require('bcryptjs');
var jwt = require('jwt-simple');
var moment = require('moment');
var config = require('../../config/config')

module.exports = {
  //权限审核中间件
    ensureAuthenticated:function ensureAuthenticated(req, res, next) {
        if (!req.header('Authorization')) {
            return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
        }
        var token = req.header('Authorization').split(' ')[1];

        var payload = null;
        try {
            payload = jwt.decode(token, config.TOKEN_SECRET);
        }
        catch (err) {
            return res.status(401).send({ message: err.message });
        }

        if (!payload.exp || payload.exp <= moment().unix()) {
            return res.status(401).send({ message: 'Token has expired' });
        }
        req.user = payload.user; 

        var tree = req.user.tree;   //获取token 并去除tree

        var url = req.originalUrl; // 获取req.originalUrl

        url = url.replace(/\//g,''); // 处理url  去掉‘／’

        if(tree.includes(url)){
            next();  
        }else{
            return res.status(401).send({ message: 'You do not have the authority' });

        }
    },
//生成jwt token
    createJWT:function createJWT(user) {

        var payload = user;
        var payload = {
            user: user,
            iat: moment().unix(),
            exp: moment().add(14, 'days').unix()
        };

        try {
            return jwt.encode(payload, config.TOKEN_SECRET);
        } catch (error) {
            return error;
        }
    }
// 增加权限认真的中间键
};